package com.taoyun.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoyun.mapper.MpFileMapper;
import com.taoyun.pojo.entity.File;
import com.taoyun.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 定时任务
 *
 * @author FengJingdong
 */
@Component
public class ScheduleTask {

    @Autowired
    private MpFileMapper mpFileMapper;
    @Autowired
    private IFileService fileService;

    /**
     * 扫描过期任务
     * 每月1号凌晨3点执行一次
     */
    @Async("scheduleExecutor")
    @Scheduled(cron = "0 0 3 1 * ?")
    public void executeFileDeleteTask() {
        // 删除放置时间超过一个星期的文件
        LocalDateTime date = LocalDateTime.now().minusWeeks(1);
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(File::getDeleteLogo, "1")
        .lt(File::getlMtime,date);

        List<File> files = mpFileMapper.selectList(queryWrapper);
        List<Integer> fileIds = files.parallelStream().
                map(File::getFileId).collect(Collectors.toList());

        fileService.deleteFromRecycleBin(fileIds);
    }

    /**
     *  删除任务线程池
     * @return Executor
     */
    @Bean
    public Executor scheduleExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("delete-schedule-");
        executor.setMaxPoolSize(8);
        executor.setCorePoolSize(4);
        executor.setQueueCapacity(0);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

}
